<template>
	<div class="personalSettingSwitch_container pr-1 pl-1">
    <div class="personalSettingSwitch_container_password br-16 padding-1" v-if="type == 3">
      <div class="password_title mb-0">{{ $t("新密码") }}</div>
      <div class="password_inp mb-0">
        <input type="password" v-model="inps.newPassword" />
      </div>
      <div class="password_title mb-0">{{ $t("再次输入密码") }}</div>
      <div class="password_inp mb-0">
        <input type="password" v-model="inps.confirmPassword" />
      </div>
      <div class="password_title mb-0">{{ $t("验证码") }}</div>
      <div class="password_yzm mb-0">
        <div class="password_inp">
          <input type="text" v-model="inps.code" />
        </div>
        <span @click="clickResendCode">{{ $t("发送") }}</span>
      </div>
      <div v-if="hasGoogleAuthenticator" class="password_title mb-0">{{ $t("谷歌验证码") }}</div>
      <div v-if="hasGoogleAuthenticator" class="password_inp mb-0">
        <input type="password" v-model="inps.googleAuthenticatorCode" />
      </div>
      <div class="password_content mb-1 mt-1">
        <p>{{ $t("您的密码应该满足以下标准：") }}</p>
        <p>&nbsp;·&nbsp;{{ $t("请输入6位数字密码") }}</p>
        <p>&nbsp;·&nbsp;{{ $t("密码应为随机组合，不要使用连续或重复的数字") }}</p>
        <p>&nbsp;·&nbsp;{{ $t("修改密码后24小时不能提现！") }}</p>
      </div>
      <button @click="passwordSubmit">{{ $t("提交") }}</button>
    </div>
    <div class="personalSettingSwitch_container_identity" v-if="type == 4">
      <div class=" mb-1" v-if="identity_info.type == 1">
        <div class="identity_box mb-1">
          <div class="identity_img">
            <img src="@/image/personalCenter/systemSettings/number1.png" alt="">
          </div>
          <div class="identity_content">
            <p class="mb-1">{{ $t("复制16位密钥,或扫描下方二维码。") }}</p>
            <span>{{ $t("16位密钥") }}</span>
            <div class="identity_key mt-1 mb-1">
              <div class="identity_key_text">{{ identity_info.key }}</div>
              <div class="identity_key_copy" @click="copyKey">{{ $t("复制") }}</div>
            </div>
            <img :src="identity_info.qrCode" alt="">
          </div>
        </div>
        <div class="identity_box mb-1">
          <div class="identity_img">
            <img src="@/image/personalCenter/systemSettings/number2.png" alt="">
          </div>
          <div class="identity_content">
            <p class="mb-1">{{ $t("打开谷歌验证器。使用您刚刚复制的16位密钥添加新的身份验证器") }}</p>
            <img src="@/image/personalCenter/systemSettings/google.png" alt="" @click="goGoogleVerify">
          </div>
        </div>
        <div class="identity_box mb-2">
          <div class="identity_img">
            <img src="@/image/personalCenter/systemSettings/number3.png" alt="">
          </div>
          <div class="identity_content">
            <p class="mb-1">{{ $t("返回APP，验证新的身份验证器") }}</p>
          </div>
        </div>
        <div class="identity_box_bottom br-16">
          {{ $t("请确保您已完成步骤2，再点击下一步。") }}
        </div>
      </div>
      <div class="mt-4 mb-3" v-else>
        <p class="identity_next_title mb-2">{{ $t("验真身份验证器") }}</p>
        <p class="identity_next_label mb-0">{{ $t("验真身份验证器") }}</p>
        <div class="identity_next_input mb-1">
          <input type="text" v-model="identity_info.googleCode" :placeholder="$t('请输入')"/>
          <!-- <span @click="handlePaste">{{ $t("粘贴") }}</span> -->
        </div>
        <p class="identity_next_text">{{ $t("请输入验证器APP生成的6位验证码") }}</p>
      </div>
      <button class="identity_btn" @click="clickIdentity">{{ identity_info.type == 1 ? $t("下一步") : $t("提交") }}</button>
    </div>
    <div class="personalSettingSwitch_container_currency" v-if="type == 1">
      <van-index-bar :index-list="indexBarList" v-if="nationList">
        <div v-for="(val , ind) in indexBarList" :key="ind" class="indexBar_item">
          <van-index-anchor :index="val">{{ val }}</van-index-anchor>
          <van-cell v-for="(item , index) in nationList[val]" :key="index" :value="item.rate" :title="item.code" @click="handleClick(item)">
            <template #icon>
              <img :src="item.flag" alt="">
            </template>
          </van-cell>
        </div>
      </van-index-bar>
      <van-empty v-if="!nationList"></van-empty>
    </div>
  </div>
</template>

<script>
import { clipboard } from '@/utils';
import { updateTradePassword , getCurrencyRate , getUserInfo , authentication , verifyGoogleCode , updateCurrency } from "@/request/personalCenter";
import { sendCodeToEmail } from "@/request/login"
export default {
  name: 'PersonalSettingSwitch',
  data(){
    return {
      type:1, // 认证类型
      inps:{ // 修改密码
        newPassword:'',
        confirmPassword:'',
        code:'',
        googleAuthenticatorCode: ''
      },
      identity_info:{ // 身份认证信息
        key: 'PECANBJMECUUZJHA',
        qrCode: 'https://th.bing.com/th/id/OIP.ARl3KLdrxBHQBgu0P8mQZwAAAA?rs=1&pid=ImgDetMain',
        googleCode: '',
        type:1,
      },
      indexBarList:[],
      nationList: null,
      email: '',
    }
  },
  mounted(){
    if(this.$route.params.type){
      this.type = this.$route.params.type
    }
    if(this.type == 1){
      this.disposeIndexBarList()
    }else if(this.type == 3){
      this.getUserInfo()
    }else if(this.type == 4){
      this.identity_info.type = 1
      this.getGoogleAuth()
    }
  },
  computed: {
    // 是否谷歌验证器
    hasGoogleAuthenticator(){
      return this.$store.state.userStore.hasGoogleAuthenticator;
    }
  },
  methods:{
    // 处理汇率索引
    disposeIndexBarList(){
			this.indexBarList = Array.from({length: 26}, (_, i) => String.fromCharCode(65 + i));
			// this.disposeData()
      this.disposeCurrencyList()
		},
    // 获取币种汇率
    disposeCurrencyList(){
      getCurrencyRate({}).then(res=>{
        if(res.code == 1){
          const grouped = {};
          res.data.forEach(item => {
            const firstLetter = item.code[0].toUpperCase(); // 获取code的第一个字母并大写
            if (!grouped[firstLetter]) {
                grouped[firstLetter] = [];
            }
              grouped[firstLetter].push(item);
          });
          
          // 过滤掉空的分组并排序
          this.indexBarList = this.indexBarList.filter(letter => grouped[letter] && grouped[letter].length > 0);
          this.nationList = grouped;
        }
      })
    },
    handleClick(item){
      // 切换币种
      updateCurrency({currency:item.code}).then(res=>{
        if(res.code == 1){
          this.$toast.success(this.$t("切换成功"))
          this.$router.go(-1)
          setTimeout(() => {
            console.log('刷新')
            window.location.reload()
          }, 500);
        }else{
          this.$toast.fail(res.msg)
        }
      })
    },
    // 获取用户邮箱
    getUserInfo(){
      getUserInfo({}).then(res=>{
        if(res.code == 1){
          this.email = res.data.username
        }
      })
    },
    clickResendCode(){
      console.log(this.email)
      // 发送验证码
      sendCodeToEmail({email:this.email,event:"changeppwd"}).then(res=>{
        if(res.code == 1){
          this.$toast(res.msg)
        }else{
          this.$toast(res.msg)
        }
      })
    },
    passwordSubmit(){
      // 更改密码完成
      // 添加发送密码逻辑并跳转回设置页
      if(this.inps.newPassword != this.inps.confirmPassword){
        this.$toast.fail(this.$t("两次密码不一致"))
        return
      }else if(!this.inps.newPassword || !this.inps.confirmPassword || !this.inps.code){
        this.$toast.fail(this.$t("请填写完整信息"))
        return
      }
      let obj = {
        password: this.inps.newPassword,
        repassword: this.inps.confirmPassword,
        captcha: this.inps.code,
        google_code:this.inps.googleAuthenticatorCode
      }
      
      updateTradePassword(obj).then(res=>{
        if(res.code == 1){
          this.$toast.success(this.$t("修改成功"))
          this.$router.go(-1)
        }else{
          this.$toast.fail(res.msg)
        }
      })
    },
    // 获取谷歌验证码
    getGoogleAuth(){
      authentication({}).then(res=>{
        console.log(res)
        if(res.code == 1){
          this.identity_info = {
            ...this.identity_info,
            key: res.data.goog_secret,
            qrCode: res.data.goog_url
          }
        }else{
          this.$toast.fail(res.msg)
        }
      })
    },
    // 跳转谷歌验证器
    goGoogleVerify(){
      const scheme = 'otpauth://';
      
      // 尝试直接打开App
      window.location.href = scheme;
      
      // 如果无法直接打开，则跳转到应用商店
      setTimeout(() => {
        if (!document.hidden) {
          // Android Play Store
          window.location.href = 'https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2';
          // iOS App Store
          window.location.href = 'https://apps.apple.com/app/google-authenticator/id388497605';
        }
      }, 1000);
    },
    clickIdentity(){
      // 身份认证按钮点击
      // console.log(123123123123 , this.identity_info.type)
      if(this.identity_info.type == 1){
        this.identity_info.type = 2
      }else{
        // 提交身份认证
        // 添加提交逻辑并跳转回设置页
        verifyGoogleCode({code:this.identity_info.googleCode}).then(res=>{
          if(res.code == 1){
            this.$toast.success(this.$t("认证成功"))
            this.$router.go(-1)
          }else{
            this.$toast.fail(res.msg)
          }
        })
      }
    },
    async copyKey(){
      try {
				await clipboard.copy(this.identity_info.key);
				this.$toast.success(this.$t('复制成功'));
			} catch {
				this.$toast.fail(this.$t('复制失败'));
			}
    },
    async handlePaste() {
      // 粘贴逻辑有问题，待测试
      // 暂时走手动粘贴
      // try {
      //   console.log('开始粘贴流程');
      //   const content = await clipboard.paste();
      //   console.log('最终获取内容:', content);
        
      //   if (content) {
      //     // ...原有处理逻辑...
      //   } else {
      //     this.$toast('检测到空内容，请确认已复制验证码');
      //   }
      // } catch (e) {
      //   console.error('完整错误堆栈:', e.stack);
      //   this.$toast('粘贴失败：' + e.message);
      // }
    }
  }
}
</script>

<style>

</style>